#include "toast.h"

Toast::Toast(const QString& text, QWidget *parent)
    : QWidget{parent}
{
    this->setFixedSize(500, 100);
    this->setWindowIcon(QIcon(":/resource/image/logo.png"));
    this->setAttribute(Qt::WA_DeleteOnClose);
    this->setStyleSheet("QDialog { background-color: white; border-radius: 10px; }");
    this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);  // 去掉菜单栏且置顶

    // 1.计算摆放位置
    QScreen *screen = QApplication::primaryScreen();  // 获取当前机器的主显示器
    int width = screen->size().width();
    int height = screen->size().height();
    int x = (width - this->width()) / 2;
    int y = height - this->height() - 100;
    this->move(x, y);

    // 2. 内容弹窗
    QHBoxLayout* layout = new QHBoxLayout(this);
    layout->setContentsMargins(20, 20, 20, 20);

    QLabel* textLabel = new QLabel(text);
    // textLabel->setWordWrap(true);
    textLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    textLabel->setStyleSheet("QLabel { font-size: 14px; } ");
    layout->addWidget(textLabel, 0, Qt::AlignCenter);

    // 3.计时2秒就挂断
    QTimer* timer = new QTimer(this);
    timer->start(2000);
    connect(timer, &QTimer::timeout, this, [=]{
        timer->stop();
        this->close();
    });
}

void Toast::showMessage(const QString &text)
{
    Toast* toast = new Toast(text);
    toast->show();
}
